package com.huiqiao.lesson10.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Component
public class AccountDao {

    @Autowired
    private DataSource dataSource;

    /**
     * 使用 JDBC 手动控制事务
     */
    public void transferByJdbc() {
        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;

        try {
            // 获取连接
            conn = dataSource.getConnection();

            // 关闭自动提交（相当于 START TRANSACTION）
            conn.setAutoCommit(false);

            // 执行SQL1 - Bob 加 100
            ps1 = conn.prepareStatement("UPDATE account SET balance = balance + 100 WHERE username = 'Bob'");
            ps1.executeUpdate();

            // 执行SQL2 - Alice 减 100
            ps2 = conn.prepareStatement("UPDATE account SET balance = balance - 100 WHERE username = 'Alice'");
            ps2.executeUpdate();

            // 提交事务（COMMIT）
            conn.commit();
            System.out.println("转账成功，事务已提交！");

        } catch (SQLException e) {
            System.err.println(" 事务回滚，原因：" + e.getMessage());
            // 出错回滚（ROLLBACK）
            try {
                if (conn != null) {
                    conn.rollback();
                    System.err.println(" 事务回滚 成功");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            // 释放资源
            try {
                if (ps1 != null) ps1.close();
                if (ps2 != null) ps2.close();
                if (conn != null) conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}
